package com.it.okdemo;

import android.os.Bundle;
import android.os.Environment;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.RelativeLayout;

import java.io.File;
import java.io.IOException;
import java.net.SocketTimeoutException;
import java.net.UnknownHostException;
import java.util.concurrent.TimeUnit;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import okhttp3.Cache;
import okhttp3.CacheControl;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Interceptor;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

public class MainActivity extends AppCompatActivity {

    @BindView(R.id.tv_1)
    Button mTv1;
    @BindView(R.id.tv_2)
    Button mTv2;
    @BindView(R.id.activity_main)
    RelativeLayout mActivityMain;

    String url =
            "http://210.75.207.51:7001/Meteorological/power_powerObserve.action?type=wind&areacode=&level=500kV";

    private  OkHttpClient client;
    private  final long cacheSize = 1024 * 1024 * 20;// 缓存文件最大限制大小20M
    private  String cacheDirectory = Environment.getExternalStorageDirectory() + "/okttpcaches"; // 设置缓存文件路径
    private  Cache cache = new Cache(new File(cacheDirectory), cacheSize);  //
    private   int cacheTime=1800;
    static {


    }


 void init(){
    //如果无法生存缓存文件目录，检测权限使用已经加上，检测手机是否把文件读写权限禁止了
    OkHttpClient.Builder builder = new OkHttpClient.Builder();
    builder.connectTimeout(60, TimeUnit.SECONDS); // 设置连接超时时间
    builder.writeTimeout(60, TimeUnit.SECONDS);// 设置写入超时时间
    builder.readTimeout(60, TimeUnit.SECONDS);// 设置读取数据超时时间
    builder.retryOnConnectionFailure(true);// 设置进行连接失败重试
    builder.cache(cache);// 设置缓存
//        builder.addInterceptor(new CacheInterceptor());
    //有网络时的拦截器
    builder.addNetworkInterceptor(rewrite_response_interceptor);
    //没网络时的拦截器
//    builder.addInterceptor(rewrite_response_interceptor_offline);
    client = builder.build();
     try {
         client.cache().evictAll();
     } catch (IOException e) {
         e.printStackTrace();
     }
 }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        ButterKnife.bind(this);
         init();
    }
    long t1=0;

    @OnClick({R.id.tv_1, R.id.tv_2, R.id.activity_main})
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.tv_1:
                /*new Thread(new Runnable() {
                    @Override
                    public void run() {
                        try {
                            OkGo.get(url).tag("1").execute();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                }).start();*/
                Request request = new Request.Builder()
                        .cacheControl(new CacheControl.Builder().noCache().maxAge(cacheTime, TimeUnit.SECONDS)
                                .build())
                        .url(url).build();

                Call call = client.newCall(request);
                t1= System.currentTimeMillis();
                System.out.println("start______________________");
                call.enqueue(new Callback() {
                    @Override
                    public void onFailure(Call call, IOException arg1) {
                        String message = "未知错误";
                        if (arg1 != null) {
                            Throwable t = arg1.getCause();
                            message = arg1.toString();
                            if (t != null) {
                                if (t instanceof SocketTimeoutException) {
                                    message = "请求超时了";
                                } else if (t instanceof UnknownHostException) {
                                    message = "UnknownHostException,无法访问该地址";
                                }

                            }
                        }
                        System.out.println(message);
                    }

                    @Override
                    public void onResponse(Call call, Response response) throws IOException {

                        if (response.isSuccessful()) {
                            System.out.println((System.currentTimeMillis()-t1)+response.body().string());
                        } else {
                            if(response.cacheResponse()!=null){
                                System.out.println("缓存"+response.cacheResponse().body().string());
                            }else {
                                System.out.println("response失败了，连接状态码为：" + response.code());
                            }
                        }

                    }
                });



                break;
            case R.id.tv_2:

                Request request2 = new Request.Builder()
                        .cacheControl(new CacheControl.Builder().maxAge(cacheTime, TimeUnit.SECONDS)
                                .build())
                        .url(url).build();

                Call call2 = client.newCall(request2);
                System.out.println("start2______________________");
                call2.enqueue(new Callback() {
                    @Override
                    public void onFailure(Call call, IOException arg1) {
                        String message = "2未知错误";
                        if (arg1 != null) {
                            Throwable t = arg1.getCause();
                            message = arg1.toString();
                            if (t != null) {
                                if (t instanceof SocketTimeoutException) {
                                    message = "2请求超时了";
                                } else if (t instanceof UnknownHostException) {
                                    message = "UnknownHostException,无法访问该地址";
                                }

                            }
                        }
                        System.out.println(message);
                    }

                    @Override
                    public void onResponse(Call call, Response response) throws IOException {

                        if (response.isSuccessful()) {
                            System.out.println(response.body().string());
                        } else {
                            if(response.cacheResponse()!=null){
                                System.out.println("缓存2"+response.cacheResponse().body().string());
                            }else {
                                System.out.println("response2失败了，连接状态码为：" + response.code());
                            }
                        }

                    }
                });




                break;
            case R.id.activity_main:
                break;
        }
    }






    public   Interceptor rewrite_response_interceptor = new Interceptor() {
        @Override
        public okhttp3.Response intercept(Chain chain) throws IOException {
            //获取retrofit @headers里面的参数，参数可以自己定义，在本例我自己定义的是cache，跟@headers里面对应就可以了
            String cache = chain.request().header("cache");
            okhttp3.Response originalResponse = chain.proceed(chain.request());
            String cacheControl = originalResponse.header("Cache-Control");
            //如果cacheControl为空，就让他TIMEOUT_CONNECT秒的缓存，本例是5秒，方便观察。注意这里的cacheControl是服务器返回的
            if (cacheControl == null) {
                //如果cache没值，缓存时间为TIMEOUT_CONNECT，有的话就为cache的值
                if (cache == null || "".equals(cache)) {
                    cache = cacheTime + "";
                }
                originalResponse = originalResponse.newBuilder()
                        .header("Cache-Control", "public, max-age=" + cache)
                        .build();
                return originalResponse;
            } else {
                return originalResponse;
            }
        }
    };






    public  Interceptor rewrite_response_interceptor_offline = new Interceptor() {
        @Override
        public okhttp3.Response intercept(Chain chain) throws IOException {
            Request request = chain.request();
            //离线的时候为7天的缓存。
            if (!NetUtils.isConnected(MainActivity.this)) {
                request = request.newBuilder()
                        .header("Cache-Control", "public, only-if-cached, max-stale="+cacheTime)
                        .build();
            }
            return chain.proceed(request);
        }
    };




}
